<template>
  <div>
    <el-button type="primary" @click="addNewClick" size="mini">新增</el-button>
    <el-drawer :withHeader="false" :visible.sync="dialog" :before-close="cancelForm" direction="rtl" :with-header="false" ref="drawer"
      size="950px">
      <div style="margin:20px">
        <el-form label-position="right" label-width="100px" :inline="true" :rules="rules" :model="form" ref="form" :disabled="disabled">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="所属项目:" style="width:100%" prop="projectId" required>
                <el-select v-model="form.projectId" clearable placeholder="所属项目..."
                  class="form-inputB" @change="getProjectId" size="small">
                  <el-option-group :key="group.value" :label="group.value" v-for="group in projectList">
                    <el-option v-for="item in group.projectList"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item.projectId"></el-option>
                  </el-option-group>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属模块:" style="width:100%" prop="moduleId" required>
                <el-cascader
                v-model="form.moduleId"
                size="small"
                @change="getModuleId"
                :key="key"
                :options="moduleList"
                :props="{label:'moduleName', value: 'moduleId', children: 'children'}"
                clearable
                placeholder="所属模块..."
                class="form-inputB">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="对应任务:" style="width:100%" prop="taskId" required>
                <el-select v-model="form.taskId" clearable placeholder="对应任务..."
                    class="form-inputB" @change="getTaskId" size="small">
                    <el-option v-for="item in taskList"
                      :key="item.taskId"
                      :label="item.decomposition"
                      :value="item.taskId">
                    </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="开发责任人:" style="width:100%">
                <el-select v-model="form.respPerson" placeholder="请选择" class="form-inputB" disabled size="small">
                  <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开发负责人:" style="width:100%" prop="devPersion" required>
                <el-select v-model="form.devPersion" placeholder="请选择" class="form-inputB" size="small">
                  <el-option v-for="item in devUserList" :key="item.userId" :label="item.userName" :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="测试负责人:" style="width:100%" prop="testPerson" required>
                <el-select v-model="form.testPerson" placeholder="请选择" class="form-inputB" size="small">
                  <el-option v-for="item in testUserList" :key="item.userId" :label="item.userName" :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="问题类型:" style="width:100%" prop="peType" required>
                <el-select v-model="form.peType" placeholder="请选择" class="form-inputB" size="small">
                  <el-option v-for="item in peType" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预计修复:" style="width:100%">
                <el-date-picker v-model="form.preRepair" type="date"
                  placeholder="选择日期" style="width:178px" value-format="yyyy-MM-dd" size="small">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划上线:" style="width:100%">
                <el-date-picker v-model="form.preOnline" type="date"
                  placeholder="选择日期" style="width:178px" value-format="yyyy-MM-dd" size="small">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="问题描述:" style="width:100%" prop="describe" required>
                <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="form.describe"
                style="width:798px" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注:" style="width:100%">
                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="form.remarks"
                  style="width:798px" size="small">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="截图:" style="width:100%; margin-bottom: 0px">
                <el-upload
                  :action=attachmentsUpload
                  list-type="picture-card"
                  :file-list="form.fileList"
                  :data="form.upload"
                  :limit="4"
                  :headers="form.headers"
                  :on-success="uploadSuccess"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <!-- 展示图片 -->
                <el-dialog :visible.sync="diaVis" :append-to-body="true">
                  <img width="100%" :src="form.dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="float:right;margin-right:10px" v-show="isView">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')" :loading="loading">
            {{ loading ? '提交中...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { upload, addEvent, editEvent } from '@/api/events'
  import { mapGetters } from 'vuex'
  export default {
    name: "PopVue",
    computed: {
      ...mapGetters([
        'attachmentsLocal',
        'attachmentsUpload'
      ])
    },
    data() {
      let checkProjectId = (rule, value, callback) => { !value?callback(new Error('请选择项目')):callback()}
      let checkDevPersion = (rule, value, callback) => { !value?callback(new Error('请选择开发人员')):callback()}
      let checkTestPersion = (rule, value, callback) => { !value?callback(new Error('请选择测试人员')):callback()}
      let checkVesrion = (rule, value, callback) => { !value?callback(new Error('请选择版本')):callback()}
      let checkTaskId = (rule, value, callback) => { value===''?callback(new Error('请选择任务')):callback()}
      let checkDecomposition = (rule, value, callback) => { !value?callback(new Error('请输入任务分解')):callback()}
      let checkDescribe = (rule, value, callback) => { !value?callback(new Error('请输入任务详情描述')):callback()}
      let checkProjectModule = (rule, value, callback) => { !value?callback(new Error('请选择所属模块')):callback()}
      let checkPeType = (rule, value, callback) => { value===''?callback(new Error('请选择问题类型')):callback()}
      return {
        diaVis: false,
        dialog: false,
        isView: true,
        loading: false,
        flag: true,
        key: 1,
        versionList: [],
        projectList: [],
        baseProjectList: [],
        userList: [],
        devUserList: [],
        testUserList: [],
        moduleList: [],
        taskList: [],
        disabled: false,
        peType: [
          {id: 0, value: '样式bug'},
          {id: 1, value: '程序bug'},
          {id: 2, value: '接口问题'},
          {id: 3, value: '页面优化'},
          {id: 5, value: '未知'}
        ],
        form: {
          peId: '',
          group: '',
          projectId: '',
          projectName: '',
          moduleId: '',
          taskId: '',
          respPerson: '',
          testPerson: '',
          peType: '',
          vesrion: '',
          devPersion: '',
          commission: '',
          preRepair: '',
          preOnline: '',
          adjustStart: '',
          decomposition: '',
          describe: '',
          selfTest: '',
          remarks: '',
          dialogImageUrl: '',
          fileList: [],
          uploadFileList: [],
          headers: { Authorization: getToken() },
          upload: { tempCode: ''},
          code: ''
        },
        timer: null,
        rules: {
          projecId: [{ validator: checkProjectId, trigger: 'blur' }],
          moduleId: [{ validator: checkProjectModule, trigger: 'blur' }],
          taskId: [{ validator: checkTaskId, trigger: 'blur' }],
          devPersion:  [{ validator: checkDevPersion, trigger: 'blur' }],
          testPerson:  [{ validator: checkTestPersion, trigger: 'blur' }],
          vesrion:  [{ validator: checkVesrion, trigger: 'blur' }],
          decomposition:  [{ validator: checkDecomposition, trigger: 'blur' }],
          describe: [{ validator: checkDescribe, trigger: 'blur' }],
          peType: [{ validator: checkPeType, trigger: 'blur' }]
        }
      };
    },
    methods: {
      readOnly(row) {
        this.editShowView(row)
        this.isView = false
      },
      uploadSuccess(response, file, fileList) {
        this.form.uploadFileList.push({
          name: file.response,
          fileName: file.response,
          type: 1,
          url: this.attachmentsLocal + file.response
        })
      },
      handleRemove(file, fileList) {
        if (typeof(file.type) == 'undefined') {
          for (let i=0; i<this.form.uploadFileList.length; i++) {
            if (this.form.uploadFileList[i].fileName===file.response) {
              this.form.uploadFileList.splice(i, 1)
            }
          }
        } else {
          for (let i=0; i<this.form.uploadFileList.length; i++) {
            if (this.form.uploadFileList[i].fileName===file.fileName) {
              this.form.uploadFileList[i].type = 2
            }
          }
        }
      },
      handlePictureCardPreview(file) {
        this.form.dialogImageUrl = file.url;
        this.diaVis = true;
      },
      handleAvatarSuccess(res, file) {
      },
      addNewClick() {
        this.flag = true
        this.dialog = true
        this.clear()
        if (typeof(this.$refs['form']) !== 'undefined') {
          this.$refs['form'].clearValidate()
        }
        this.getParentData()
        this.projectList.length>0?this.form.projectName=this.projectList[0].projectList[0].projectName:console.log('项目列表为空，请先维护项目')
        let date = new Date()
        this.form.upload.tempCode = "TMP" + date.getFullYear() + date.getMonth() + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + Math.round(Math.random() * 1000)
        this.isView = true
      },
      editShowView(row) {
        this.dialog = true
        this.flag = false
        this.clear()
        this.getParentData()
        this.form.peId = row.peId
        this.form.group = row.group
        this.form.projectId = row.projectId
        this.form.taskId = row.taskId
        this.initModuleList(row.projectId)
        this.form.moduleId = [row.lv1ModuleId, row.lv2ModuleId]
        this.getModuleId(this.form.moduleId)
        this.form.respPerson = row.respPerson
        this.form.testPerson = row.testPerson
        this.form.devPersion = row.devPerson
        this.form.peType = row.peType
        this.form.preRepair = row.preRepair
        this.form.preOnline = row.preOnline
        this.form.describe = row.describe
        this.form.upload.tempCode = row.tempCode
        this.form.code = row.peCode
        this.form.remarks = row.remarks
        if (row.attachments != null) {
          row.attachments.forEach(a => {
            this.form.fileList.push({
              id: a.id,
              name: a.fileName,
              fileName: a.fileName,
              url: this.attachmentsLocal + a.fileName,
              type: a.type
            })
          })
          this.form.uploadFileList = JSON.parse(JSON.stringify(this.form.fileList))
          this.isView = true
        }
      },
      clear() {
        this.key++
        this.form.peId = ''
        this.form.group = ''
        this.form.projectId = ''
        this.form.taskId = ''
        this.form.moduleId = []
        this.form.respPerson = ''
        this.form.testPerson = ''
        this.form.devPersion = ''
        this.taskList = []
        this.moduleList = []
        this.form.peType = ''
        this.form.preRepair = ''
        this.form.preOnline = ''
        this.form.describe = ''
        this.form.upload.tempCode = ''
        this.form.code = ''
        this.form.remarks = ''
        this.form.fileList = []
        this.form.uploadFileList = []
      },
      getParentData() {
        this.form.group = this.$parent.$parent.popData.group
        this.versionList = this.$parent.$parent.versionList
        this.projectList = this.$parent.$parent.projectList
        this.userList = this.$parent.$parent.popData.userList
        this.baseProjectList = this.$parent.$parent.popData.projectList
        this.devUserList = []
        this.testUserList = []
        this.userList.length>0?this.userList.forEach(element=>{element.role==="leader"||element.role==="developer"?this.devUserList.push(element):this.testUserList.push(element)}):console.log("用户列表为空，请先维护组内用户")

      },
      initModuleList(projectId) {
        this.moduleList = []
        for (let i=0; i<this.baseProjectList.length; i++) {
          if (projectId===this.baseProjectList[i].projectId) {
            this.moduleList = this.baseProjectList[i].modules
          }
        }
      },
      getProjectId() {
        for (let index = 0; index < this.baseProjectList.length; index++) {
          if (this.form.projectId===this.baseProjectList[index].projectId) {
            this.moduleList = this.baseProjectList[index].modules
            if (this.baseProjectList[index].modules.length>0) {
              this.form.moduleId = this.baseProjectList[index].modules[0].moduleId
            }
          }
        }
      },
      getModuleId(value) {
        let a = value[0]
        let b = value[1]
        for (let index = 0; index < this.moduleList.length; index++) {
          if (this.moduleList[index].moduleId===a) {
            let childList = this.moduleList[index].children
            if (childList != null) {
              for (let j = 0; j < childList.length; j++) {
                if (childList[j].moduleId===b) {
                  this.taskList = childList[j].tasks
                }
              }
            }
          }
        }
      },
      getTaskId(value) {
        if (value === '') {
          this.form.respPerson = ''
          return
        }
        for (let index = 0; index < this.taskList.length; index++) {
          if (this.taskList[index].taskId===value) {
            this.form.respPerson = this.taskList[index].devPerson
            if (this.form.devPersion==='') {
              this.form.devPersion = this.taskList[index].devPerson
            }
          }
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true
            this.disabled = true
            this.sleep(800).then( _ => {
              this.flag?
              addEvent(this.form).then(response => {
                if (response === 4000) {
                  return
                }
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
                this.loading = false
                this.disabled = false
                this.dialog = false
                this.$parent.$parent.handleClickSerach()
                this.clear()
              }):
              editEvent(this.form).then(response => {
                if (response === 4000) {
                  return
                }
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loading = false
                this.disabled = false
                this.$parent.$parent.handleClickSerach()
                this.dialog = false
                this.clear()
              })
            })
          }
        });
      },
      sleep(time) {
        return new Promise((resolve) => {
          setTimeout(resolve, time)
        });
      },
      cancelForm() {
        this.loading = false
        this.dialog = false
        this.sleep(100).then( _ => {
          this.clear()
          this.$refs['form'].clearValidate()
        })
      },
    },
  }

</script>

<style>
.el-form-item__content{
  margin-left:0 !important;
}
.form-inputA{
      width: 798px;
}
.form-inputB{
      width: 178px;
}
.el-col.el-col-8 {
  width: 310px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    line-height: 55px;
    text-align: center;
  }
  .avatar {
    width: 110px;
    height: 110px;
    display: block;
  }
.el-upload-list__item {
  margin-bottom: 0 !important;
}
</style>
